package chrome.entity;

import chrome.GetClass.PackageClasses;
import chrome.Interface.SerializeObj;
import com.alibaba.fastjson.JSON;
import commons.entity.NativeCp;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ChromeUtil {
    private static final Logger LOGGER = LogManager.getLogger(ChromeUtil.class);
    public static void writeObjectToJsonFile(Object obj,String path){
        String text = JSON.toJSONString(obj);
        File file = new File(path + obj.getClass().getSimpleName()+".json");
        System.out.println(path + obj.getClass().getSimpleName());
        try {
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(text);
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 自动在 指定路径下 生成 指定包下 所有继承serializeObj类的json文件
     * @param args
     */
    public static void main(String[] args) {
        List<Class<?>> classList = new ArrayList<>();
        String  packageName = "chrome.entity";
        String  path = NativeCp.getUserDir() + "/config/CHROME/";
        try {
            classList = PackageClasses.getClasses(packageName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Object tempObj = null;
        SerializeObj serializeObj = null;
        for (Class<?> classObj : classList){
            try {
                tempObj = classObj.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if(tempObj instanceof SerializeObj ){
                serializeObj = (SerializeObj)tempObj;

                writeObjectToJsonFile(serializeObj.GenerateJsonObj(),path);
            }
        }
    }
}
